package com.leyou.auth.service.impl;

import com.auth.pojo.UserInfo;
import com.auth.utils.JwtUtils;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.UserMapper;
import com.leyou.auth.service.AuthService;
import com.leyou.user.pojo.User;
import com.leyoucommon.utils.CodecUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @version 1.0.0
 * @Author yong.Mr
 * @data 2019-8-9
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private JwtProperties properties;

    @Autowired
    private UserMapper userMapper;

    public String accredit(String username, String password,User user) {

        try {

            // 调用微服务，执行查询
            //User user = this.userClient.queryUser(username, password);
            // 如果查询结果为null，则直接返回null
            if (user == null) {
                return null;
            }

            // 如果有查询结果，则生成token
            String token = JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()),
                    properties.getPrivateKey(), properties.getExpire());
            return token;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User queryUser(String username, String password) {
        // 查询
        User record = new User();
        record.setUsername(username);
        User user = this.userMapper.selectOne(record);
        // 校验用户名
        if (user == null) {
            return null;
        }
        // 校验密码
        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }
        // 用户名密码都正确
        return user;
    }
}
